package com.itheima.health.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.health.common.PageParam;
import com.itheima.health.common.ResultPageData;
import com.itheima.health.mapper.CheckGroupDao;
import com.itheima.health.mapper.SetmealAndCheckGroupDao;
import com.itheima.health.mapper.SetmealDao;
import com.itheima.health.model.pojos.Setmeal;
import com.itheima.health.model.pojos.SetmealAndCheckGroup;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private SetmealAndCheckGroupDao setmealAndCheckGroupDao;
    /**
     * 套餐分页查询
     * @param pageParam
     * @return
     */
    public ResultPageData findPage(PageParam pageParam){
        Integer currentPage = pageParam.getCurrentPage();
        Integer pageSize = pageParam.getPageSize();
        IPage<Setmeal> page = new Page<>(currentPage,pageSize);

        LambdaQueryWrapper<Setmeal> query = new LambdaQueryWrapper<>();
        query.like(StringUtils.isNotBlank(pageParam.getQueryString()),Setmeal::getCode,pageParam.getQueryString())
                .or().like(StringUtils.isNotBlank(pageParam.getQueryString()),Setmeal::getHelpCode,pageParam.getQueryString())
                .or().like(StringUtils.isNotBlank(pageParam.getQueryString()),Setmeal::getName,pageParam.getQueryString());
        IPage<Setmeal> pageData = setmealDao.selectPage(page, query);
        long total = pageData.getTotal();
        List<Setmeal> records = pageData.getRecords();

        ResultPageData resultPageData = new ResultPageData();
        resultPageData.setTotal(total);
        resultPageData.setRows(records);
        return resultPageData;
    }


    @Transactional
    public void insert(Setmeal setmeal, List<Integer> checkgroupIds) {
        //添加套餐分为2步
        //1.添加套餐
        //2.添加套餐检查组关联表
        //1.添加套餐
        int insert = setmealDao.insert(setmeal);
        //遍历集合,挨个插入
        for (Integer checkgroupId : checkgroupIds) {
            SetmealAndCheckGroup setmealAndCheckGroup = new SetmealAndCheckGroup(setmeal.getId(),checkgroupId);
            setmealAndCheckGroupDao.insert(setmealAndCheckGroup);
        }

    }
}
